package com.offcn.user.controller;

import com.alibaba.fastjson.JSON;
import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.user.pojo.User;
import com.offcn.user.service.UserService;
import com.offcn.utils.JwtUtil;
import com.offcn.utils.PhoneFormatCheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public Result addUser(@RequestBody User user){

        // 校验注册的用户 的 手机号 和 用户名 是否已经存在
        if (!userService.checkSmsCode(user.getPhone(),user.getCode())) {
            return new Result(false,StatusCode.ERROR,"验证码错误，请重试");
        }
        try {
            userService.add(user);
            return new Result(true, StatusCode.OK,"用户注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"用户注册失败");
        }
    }

    @GetMapping("/sendCode")
    public Result sendCode(String phone){
        if (!PhoneFormatCheckUtils.isChinaPhoneLegal(phone)) {
            return new Result(false,StatusCode.ERROR,"手机格式错误");
        }
        try {
            userService.createSmsCode(phone);
            return new Result(true,StatusCode.OK,"验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"验证码发送失败");
        }
    }

    @GetMapping("/login")
    public Result login(String username, String password, HttpServletResponse response){
        // 加密器
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        User user = userService.findByUsername(username);
        if (user != null && encoder.matches(password,user.getPassword())) {
            // 存储登录成功的用户信息，方便将来验证用户信息和获取用户信息，Session 不一致的情况 ，jwt 和 session一致化处理 （session存储redis）
            // 替换session ==> 对存储的数据进行加密 + 可以校验
            // 令牌的Id
            String id = UUID.randomUUID().toString();
            // 令牌携带的内容
            Map<String, String> map = new HashMap<>();
            map.put("username",username);
            map.put("role","user");
            String json = JSON.toJSONString(map);
            // 生成令牌
            String jwt = JwtUtil.createJwt(id, json, null);
            // 将令牌存储到Cookie
            Cookie cookie = new Cookie("Authorization",jwt);
            cookie.setPath("/"); // 必须有
            response.addCookie(cookie);
            return new Result(true,StatusCode.OK,"登录成功");
        }else{
            return new Result(false,StatusCode.LOGINERROR,"登录失败");

        }
    }

    @GetMapping("/{username}")
    public Result<User> findUserByUsername(@PathVariable("username") String username){
        User user = userService.findByUsername(username);
        return new Result<>(true,StatusCode.OK,user,"查询成功");
    }
}
